const ShopCar = require('../../models/good/shopcar');
class ShopCarService {
    static async getShopCarList({ pageNum = 1, pageSize = 10 }, data) {
        try {
            // 参数类型转换和验证
            const pageNumInt = parseInt(pageNum) || 1;
            const pageSizeInt = parseInt(pageSize) || 10;
            
            // 限制pageSize最大值，防止恶意请求
            const limit = Math.min(pageSizeInt, 100);
            const skip = (pageNumInt - 1) * limit;
            
            // 构建查询条件
            const query = {};
            if (data?.userId) {
                query.userId = data.userId;
            }
            if (data?.sid) {
                query.sid = data.sid;
            }
            
            const total = await ShopCar.countDocuments(query);
            const shopCarList = await ShopCar.find(query)
                .skip(skip)
                .limit(limit)
                .populate("userId", "-password")
                .populate({
                    path: "goodId",
                    populate: [
                        { path: "categoryId" },
                        { path: "tagId" }
                    ]
                })
                .lean();
                
            return {
                total,
                page: pageNumInt,
                totalPages: Math.ceil(total / limit),
                list: shopCarList
            };
        } catch (error) {
            throw new Error(`获取购物车列表失败: ${error.message}`);
        }
    }
    static async getShopCarById(shopCarId) {
        console.log(shopCarId, '22');
        let res = await ShopCar.findById(shopCarId).populate("userId", "-password").populate({
            path: "goodId",
            populate: [
                { path: "categoryId" },
                { path: "tagId" }
            ]
        }).lean();
        return res
    }
    static async createShopCar(shopCarData) {
        try {
            // 验证必要字段
            if (!shopCarData.userId || !shopCarData.goodId || !shopCarData.sid) {
                throw new Error('缺少必要的购物车信息');
            }
            
            // 检查是否已存在相同的购物车项（相同用户、商品和分组）
            const existingItem = await ShopCar.findOne({
                userId: shopCarData.userId,
                goodId: shopCarData.goodId,
                sid: shopCarData.sid
            });
            
            if (existingItem) {
                // 如果已存在，更新数量而不是创建新项
                const newQuantity = (existingItem.quantity || 0) + (shopCarData.quantity || 1);
                return await ShopCar.findByIdAndUpdate(
                    existingItem._id, 
                    { quantity: newQuantity }, 
                    { new: true }
                );
            }
            
            return await ShopCar.create(shopCarData);
        } catch (error) {
            throw new Error(`创建购物车失败: ${error.message}`);
        }
    }
    
    static async updateShopCar(shopCarId, shopCarData) {
        try {
            // 移除不应被更新的字段
            delete shopCarData.userId;
            delete shopCarData.goodId;
            delete shopCarData.sid;
            delete shopCarData._id;
            
            const result = await ShopCar.findByIdAndUpdate(
                shopCarId, 
                { $set: shopCarData }, 
                { new: true }
            );
            
            return result;
        } catch (error) {
            throw new Error(`更新购物车失败: ${error.message}`);
        }
    }
    static async deleteShopCar(shopCarId) {
        try {
            return await ShopCar.findByIdAndDelete(shopCarId);
        } catch (error) {
            throw new Error(`删除购物车项失败: ${error.message}`);
        }
    }

    static async deleteShopCarAll(userId) {
        try {
            return await ShopCar.deleteMany({ userId });
        } catch (error) {
            throw new Error(`清空购物车失败: ${error.message}`);
        }
    }
    
    static async deleteShopCarBySidAndUserId(sid, userId) {
        try {
            return await ShopCar.deleteMany({ sid, userId });
        } catch (error) {
            throw new Error(`删除购物车分组失败: ${error.message}`);
        }
    }
}
module.exports = ShopCarService;